package com.xiaoxin.service;

import cn.hutool.core.collection.CollUtil;
import com.xiaoxin.autoconfig.template.AipTemplate;
import com.xiaoxin.autoconfig.template.OssTemplate;
import com.xiaoxin.commons.utils.Constants;
import com.xiaoxin.dubbo.api.RecommendUserApi;
import com.xiaoxin.dubbo.api.UserInfoApi;
import com.xiaoxin.dubbo.api.UserLikeApi;
import com.xiaoxin.dubbo.api.VisitorsApi;
import com.xiaoxin.exception.BusinessException;
import com.xiaoxin.interceptor.UserHolder;
import com.xiaoxin.model.domain.UserInfo;
import com.xiaoxin.model.mongo.RecommendUser;
import com.xiaoxin.model.mongo.UserLike;
import com.xiaoxin.model.mongo.Visitors;
import com.xiaoxin.model.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xiaoxiaode
 * @date 2021-08-29-13:33
 **/
@SuppressWarnings("all")
@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipTemplate aipTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private VisitorsApi visitorsApi;


    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /*
     * 根据id查询
     */
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        // 将图片上传到阿里云
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        // 调用百度云判断是否包含人脸
        boolean detect = aipTemplate.detect(url);
        // 如果不包含人脸,抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        } else {
            // 包含人脸,调用api更新
            // 只更新id与头像
            UserInfo userinfo = new UserInfo();
            userinfo.setId(id);
            userinfo.setAvatar(url);
            userInfoApi.update(userinfo);
        }
    }


    /*
     * 根据id查询
     */
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, vo);//copy同名同类型的属性
        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    /*
     * 更新
     * */
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }


    /*
     * 互相喜欢，喜欢，粉丝 - 统计
     * */
    public Map<String, Integer> counts() {
        Long userId = UserHolder.getId();
        // 我喜欢的人列表
        List<UserLike> userLikes = userLikeApi.likeCounts(userId);
        if (CollUtil.isEmpty(userLikes)) {
            userLikes = new ArrayList<>();
        }
        // 互相喜欢
        List<Long> likeUserId = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        List<UserLike> likesToo = userLikeApi.likeToo(userId, likeUserId);
        if (CollUtil.isEmpty(likesToo)) {
            likesToo = new ArrayList<>();
        }
        // 粉丝
        List<UserLike> likeMes = userLikeApi.likeMe(userId);
        if (CollUtil.isEmpty(likeMes)) {
            likeMes = new ArrayList<>();
        }
        Map<String, Integer> map = new HashMap<>();
        map.put("eachLoveCount", likesToo.size());
        map.put("loveCount", userLikes.size());
        map.put("fanCount", likeMes.size());
        return map;
    }


    /*
     * 互相喜欢，喜欢，粉丝 - 详情
     * */
    public PageResult FriendsVoCounts(Integer page, Integer pagesize, String type) {
        Long userId = UserHolder.getId();
        if ("2".equals(type)) {
            // 我喜欢的人列表
            List<UserLike> userLikes = userLikeApi.likeCounts(userId);
            if (CollUtil.isEmpty(userLikes)) {
                return new PageResult();
            }
            List<Long> likeUserIds = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
            Map<Long, UserInfo> infoMap = userInfoApi.findByIds(likeUserIds, null);
            List<FriendsVo> vos = new ArrayList<>();
            for (Long likeUserId : likeUserIds) {
                RecommendUser recommendUser = recommendUserApi.findScore(userId, likeUserId);
                UserInfo userInfo = infoMap.get(likeUserId);
                FriendsVo vo = FriendsVo.init(userInfo, recommendUser);
                vo.setAlreadyLove(true);
                vos.add(vo);
            }
            return new PageResult(page, pagesize, 0L, vos);
        } else if ("1".equals(type)) {
            // 互相喜欢列表
            // 我喜欢的人
            List<UserLike> userLikes = userLikeApi.likeCounts(userId);
            if (CollUtil.isEmpty(userLikes)) {
                return new PageResult();
            }
            // 我喜欢的人id
            List<Long> likeUserIds = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
            List<UserLike> likesToo = userLikeApi.likeToo(userId, likeUserIds);
            if (CollUtil.isEmpty(likesToo)) {
                return new PageResult();
            }
            // 我相互喜欢的人的id
            List<Long> ids = CollUtil.getFieldValues(likesToo, "likeUserId", Long.class);
            Map<Long, UserInfo> infoMap = userInfoApi.findByIds(ids, null);
            List<FriendsVo> vos = new ArrayList<>();
            for (Long likeUserId : ids) {
                RecommendUser recommendUser = recommendUserApi.findScore(userId, likeUserId);
                UserInfo userInfo = infoMap.get(likeUserId);
                FriendsVo vo = FriendsVo.init(userInfo, recommendUser);
                vo.setAlreadyLove(true);
                vos.add(vo);
            }
            return new PageResult(page, pagesize, 0L, vos);
        } else if ("3".equals(type)) {
            // 粉丝
            List<UserLike> likeMes = userLikeApi.likeMe(userId);
            if (CollUtil.isEmpty(likeMes)) {
                return new PageResult();
            }
            // 获取粉丝id
            List<Long> likeUserIds = CollUtil.getFieldValues(likeMes, "userId", Long.class);
            Map<Long, UserInfo> infoMap = userInfoApi.findByIds(likeUserIds, null);
            List<FriendsVo> vos = new ArrayList<>();
            for (Long likeUserId : likeUserIds) {
                RecommendUser recommendUser = recommendUserApi.findScore(userId, likeUserId);
                UserInfo userInfo = infoMap.get(likeUserId);
                Boolean isLike = userLikeApi.booleanLike(userId, likeUserId);
                FriendsVo vo = FriendsVo.init(userInfo, recommendUser);
                vo.setAlreadyLove(isLike);
                vos.add(vo);
            }
            return new PageResult(page, pagesize, 0L, vos);
        } else if ("4".equals(type)) {
            // 谁看过我
            String key = Constants.VISITORS_USER_KEY;
            String hashKey = String.valueOf(UserHolder.getId());
            String value = (String) redisTemplate.opsForHash().get(key, hashKey);
            Long date = StringUtils.isEmpty(value) ? null : Long.valueOf(value);
            // 查询数据列表 list<visitors>
            List<Visitors> visitors = visitorsApi.find(date, UserHolder.getId());
            if (CollUtil.isEmpty(visitors)) {
                return new PageResult();
            }
            // 提取用户id
            List<Long> ids = CollUtil.getFieldValues(visitors, "visitorUserId", Long.class);
            // 查看用户详情
            Map<Long, UserInfo> infoMap = userInfoApi.findByIds(ids, null);
            // 构造返回
            List<FriendsVo> vos = new ArrayList<>();
            for (Long visitorUserId : ids) {
                RecommendUser recommendUser = recommendUserApi.findScore(userId, visitorUserId);
                UserInfo userInfo = infoMap.get(visitorUserId);
                Visitors visitor = visitorsApi.findOne(userId, visitorUserId);
                FriendsVo vo = FriendsVo.init(userInfo, recommendUser);
                redisTemplate.opsForHash().put(key, hashKey, visitor.getDate().toString());
                vos.add(vo);
            }
            return new PageResult(page, pagesize, 0L, vos);
        }
        return new PageResult();
    }

}
